import java.util.ArrayList;
import java.util.List;

/**
 * @program: LeetCode
 * @description: LeetCode : 剑指offer 54 二叉搜索树找第k大的数
 * @author: WXY
 * @create: 2022-12-10 20:15
 * @Version 1.0
 **/


public class Num054_kthLargest {
    public class TreeNode {
        int val;
        TreeNode left;
        TreeNode right;

        TreeNode(int x) {
            val = x;
        }
    }
    private int ans = 0, count = 0;

    public int kthLargest(TreeNode root, int k) {
        process(root, k);
        return ans;
    }

    private void process(TreeNode root, int k) {
        if (root.right != null) {
            process(root.right, k);
        }
        if (++count == k) {
            ans = root.val;
            return;
        }
        if (root.left != null) {
            process(root.left, k);
        }
    }






    public int kthLargest1(TreeNode root, int k) {
        List<Integer> list = new ArrayList<>();
        process(root, list);
        return list.get(list.size() - k);
    }

    private void process(TreeNode root, List list) {
        if (root == null)return;
        if (root.left != null) process(root.left, list);
        list.add(root.val);
        if (root.right != null) process(root.right, list);
    }
}
